<template>
    <div class="common-layout">
        <el-container>
            <el-main style="padding-bottom: 80px;">
                <el-form ref="salesFormRef" :model="salesForm" :rules="rules" label-width="120px"
                    :disabled="isDetailMode">
                    <el-card class="card-block">
                        <template #header>
                            <span class="card-title">基础信息</span>
                        </template>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="销售单号" prop="salesOrderNo">
                                    <el-input v-model="salesForm.salesOrderNo" placeholder="自动获取系统编号" readonly />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="销售日期" prop="salesOrderDate">
                                    <el-date-picker v-model="salesForm.salesOrderDate" type="date"
                                        value-format="YYYY-MM-DD" placeholder="请选择" style="width: 100%" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="客户名称" prop="customerId">
                                    <div class="inline-input">
                                        <el-select v-model="salesForm.customerId" placeholder="请选择" filterable clearable
                                            style="flex: 1" @change="handleCustomerChange">
                                            <el-option v-for="item in customerOptions" :key="item.customerId"
                                                :label="item.customerName" :value="String(item.customerId)" />
                                        </el-select>
                                        <el-button type="text" class="link-btn"
                                            @click="gotoCreateCustomer">设置</el-button>
                                    </div>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="联系人">
                                    <el-input v-model="salesForm.salesContact" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="联系方式">
                                    <el-input v-model="salesForm.salesContactPhone" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="销售部门" prop="organizationId">
                                    <el-input v-model="salesForm.organizationName" placeholder="请选择" readonly
                                        @click="openOrgDialog">
                                        <template #suffix>
                                            <el-button v-if="salesForm.organizationId" text
                                                @click.stop="clearOrgSelection">
                                                <el-icon>
                                                    <Close />
                                                </el-icon>
                                            </el-button>
                                            <el-button text @click.stop="openOrgDialog">···</el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="销售负责人" prop="userId">
                                    <el-input v-model="salesForm.userName" placeholder="请选择" readonly
                                        @click="openUserDialog">
                                        <template #suffix>
                                            <el-button v-if="salesForm.userId" text @click.stop="clearUserSelection">
                                                <el-icon>
                                                    <Close />
                                                </el-icon>
                                            </el-button>
                                            <el-button text @click.stop="openUserDialog">···</el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-form-item label="备注">
                                    <el-input v-model="salesForm.remark" type="textarea" :rows="3" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>

                    <el-card class="card-block">
                        <template #header>
                            <div class="detail-header">
                                <span class="card-title">销售明细</span>
                                <div class="detail-actions" v-if="isEditMode">
                                    <el-button type="primary" @click="openProductDialog">新增</el-button>
                                    <el-button type="danger" plain :disabled="!selectedDetailRows.length"
                                        @click="removeSelectedDetails">
                                        移除
                                    </el-button>
                                </div>
                            </div>
                        </template>
                        <el-table ref="detailTableRef" :data="salesDetails" border style="width: 100%"
                            highlight-current-row @selection-change="handleDetailSelectionChange"
                            :empty-text="isEditMode ? '请先通过新增按钮选择货品' : '暂无销售明细'">
                            <el-table-column v-if="isEditMode" type="selection" width="50" />
                            <el-table-column type="index" label="序号" width="60" />
                            <el-table-column prop="productName" label="货品名称" min-width="160" />
                            <el-table-column prop="productCode" label="货品编号" min-width="140" />
                            <el-table-column label="规格型号" min-width="160">
                                <template #default="{ row }">
                                    <el-select v-model="row.specificationModel" placeholder="请选择" style="width: 140px"
                                        filterable clearable @change="handleSpecificationChange(row)">
                                        <template v-if="row.unitGroups && row.unitGroups.length > 0">
                                            <template v-for="group in row.unitGroups" :key="group.label">
                                                <el-option-group :label="group.label">
                                                    <el-option v-for="option in group.options"
                                                        :key="`group-${option.value}`" :label="option.label"
                                                        :value="option.value">
                                                        <span>{{ option.label }}</span>
                                                        <span v-if="option.description" class="unit-desc">
                                                            {{ option.description }}
                                                        </span>
                                                    </el-option>
                                                </el-option-group>
                                            </template>
                                        </template>
                                        <el-option-group v-if="unitOptions.length > 0" label="所有单位">
                                            <el-option v-for="unit in unitOptions" :key="unit.unitId"
                                                :label="unit.unitName" :value="unit.unitName">
                                                {{ unit.unitName }}
                                            </el-option>
                                        </el-option-group>
                                        <template v-if="unitOptions.length === 0">
                                            <el-option v-for="(unit, index) in DEFAULT_UNIT_OPTIONS" :key="index"
                                                :label="unit" :value="unit">
                                                {{ unit }}
                                            </el-option>
                                        </template>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" min-width="120">
                                <template #default="{ row }">
                                    {{ row.unitName || '--' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="productTypeName" label="货品类型" min-width="120" />
                            <el-table-column prop="currentStock" label="当前库存" width="100" />
                            <el-table-column label="* 销售数量" width="130">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.quantity" :min="1" :precision="0"
                                        controls-position="right" placeholder="必填" :value-on-clear="1"
                                        @change="updateDetailAmount(row)" />
                                </template>
                            </el-table-column>
                            <el-table-column label="* 销售单价" width="140">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.unitPrice" :min="0.01" :precision="2"
                                        controls-position="right" placeholder="必填" :value-on-clear="0.01"
                                        @change="updateDetailAmount(row)" />
                                </template>
                            </el-table-column>
                            <el-table-column label="金额" width="120">
                                <template #default="{ row }">
                                    ¥{{ row.amount?.toFixed(2) || '0.00' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" min-width="160">
                                <template #default="{ row }">
                                    <el-input v-model="row.remark" placeholder="可填写补充说明" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="80" fixed="right" v-if="isEditMode">
                                <template #default="scope">
                                    <el-button link type="danger" size="small"
                                        @click="removeDetail(scope.$index)">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <div class="detail-summary" v-if="salesDetails.length">
                            <span>货品种类：{{ totalProductKinds }}</span>
                            <span>货品数量：{{ totalProductQuantity }}</span>
                            <span>总金额：¥{{ totalProductAmount.toFixed(2) }}</span>
                        </div>
                    </el-card>
                </el-form>
            </el-main>
        </el-container>

        <el-dialog v-model="orgDialogVisible" title="选择部门" width="480px">
            <el-input v-model="orgSearchText" placeholder="搜索部门名称" clearable class="dialog-search" />
            <el-tree :data="filteredOrgTree" node-key="organizationId" :props="orgTreeProps" highlight-current
                default-expand-all @node-click="handleSelectOrg" style="max-height: 360px; overflow: auto;" />
            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="orgDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmOrg">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog v-model="userDialogVisible" title="选择人员" width="480px">
            <el-input v-model="userSearchText" placeholder="搜索人员名称" clearable class="dialog-search" />
            <el-table :data="filteredUserList" height="360" border @row-click="handleSelectUser"
                style="cursor: pointer;">
                <el-table-column prop="userName" label="姓名" />
                <el-table-column prop="organizationName" label="部门" />
            </el-table>
            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="userDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmUser">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog v-model="productDialogVisible" title="添加货品" width="900px">
            <el-form :inline="true" :model="productSearchForm" class="product-search-form">
                <el-form-item>
                    <el-input v-model="productSearchForm.keyword" placeholder="请输入货品编号/名称" clearable />
                </el-form-item>
                <el-form-item>
                    <el-select v-model="productSearchForm.unit" placeholder="请选择单位" clearable filterable>
                        <el-option v-for="option in productUnitOptions" :key="option" :label="option" :value="option" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="resetProductSearch">重置</el-button>
                    <el-button type="primary" @click="searchProducts">查询</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="productList" border height="420" v-loading="productTableLoading"
                @selection-change="handleProductSelectionChange">
                <el-table-column type="selection" width="50" />
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="productCode" label="货品编号" min-width="140" />
                <el-table-column prop="productName" label="货品名称" min-width="160" />
                <el-table-column label="规格型号" min-width="120">
                    <template #default="{ row }">
                        {{ row.productUnit || row.unitDisplay || row.mainUnit || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="单位" min-width="120">
                    <template #default="{ row }">
                        {{ row.productSpecification || row.productspecification || row.specification || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="producttypeName" label="货品类型" min-width="120" />
                <el-table-column prop="inventoryCurrtnumber" label="当前库存" min-width="100" />
                <el-table-column prop="productOutMoney" label="销售单价" min-width="120">
                    <template #default="{ row }">
                        ¥{{ formatProductPrice(row) }}
                    </template>
                </el-table-column>
            </el-table>

            <div class="product-pagination">
                <el-pagination v-model:current-page="productPagination.pageindex"
                    v-model:page-size="productPagination.pagesize" :page-sizes="[10, 20, 50]"
                    layout="total, sizes, prev, pager, next" :total="productPagination.total"
                    @size-change="handleProductSizeChange" @current-change="handleProductCurrentChange" />
            </div>
            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="productDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmProductSelection">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <div class="fixed-footer">
            <div class="footer-content">
                <el-button @click="goBack">关闭</el-button>
                <el-button v-if="isEditMode" @click="resetForm">重置</el-button>
                <el-button v-if="isEditMode" type="primary" :loading="saving" @click="handleSave">保存修改</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import myaxios from '@/http/MyAxios'
import moment from 'moment'

const router = useRouter()
const route = useRoute()

const salesFormRef = ref<FormInstance>()

const salesForm = reactive({
    salesOrderNo: '',
    salesOrderDate: '',
    customerId: '',
    customerName: '',
    salesContact: '',
    salesContactPhone: '',
    organizationId: '',
    organizationName: '',
    userId: '',
    userName: '',
    remark: '',
})

const isDetailMode = computed(
    () => route.name === 'DetailSalesOrder' || route.query.mode === 'detail',
)
const isEditMode = computed(() => !isDetailMode.value)
const detailLoading = ref(false)
const currentSalesOrderId = ref<string | number | null>(null)

const rules = {
    salesOrderNo: [{ required: true, message: '销售单号不能为空', trigger: 'blur' }],
    salesOrderDate: [{ required: true, message: '请选择销售日期', trigger: 'change' }],
    customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
    organizationId: [{ required: true, message: '请选择销售部门', trigger: 'change' }],
    userId: [{ required: true, message: '请选择销售负责人', trigger: 'change' }],
}

interface CustomerItem {
    customerId: string | number
    customerName: string
    linkMan?: string
    linkPhone?: string
}

interface OrganizationItem {
    organizationId: string | number
    organizationParentId?: string | number | null
    organizationName: string
    children?: OrganizationItem[]
}

interface UserItem {
    userId: string | number
    userName: string
    organizationId?: string | number
    organizationName?: string
}

interface UnitItem {
    unitId: string | number
    unitCode: string
    unitName: string
    unitState?: number
}

interface UnitOption {
    label: string
    value: string
    description?: string
}

interface UnitOptionGroup {
    label: string
    options: UnitOption[]
}

interface SalesDetailItem {
    lineId: string
    salesOrderDetailId?: string | number | null
    productId: string | number
    productName: string
    productCode: string
    specificationModel?: string
    specification?: string
    unitName?: string
    unit?: string
    unitId?: string | number | null
    unitGroups?: UnitOptionGroup[]
    productTypeName?: string
    currentStock?: number
    quantity: number | null | undefined
    unitPrice: number
    amount: number
    remark: string
}

interface ProductListItem {
    productId: string | number
    productCode: string
    productName: string
    producttypeName?: string
    productSpecification?: string
    productspecification?: string
    specification?: string
    productUnit?: string
    inventoryCurrtnumber?: number
    productOutMoney?: number
    unitDisplay?: string
    mainUnit?: string
    [key: string]: any
}

const customerOptions = ref<CustomerItem[]>([])
let customerLoadPromise: Promise<void> | null = null

const orgDialogVisible = ref(false)
const orgTreeData = ref<OrganizationItem[]>([])
const orgNameMap = ref<Record<string, string>>({})
const orgSearchText = ref('')
const selectedOrgNode = ref<OrganizationItem | null>(null)
let orgLoadPromise: Promise<void> | null = null

const orgTreeProps = {
    children: 'children',
    label: 'organizationName',
}

const userDialogVisible = ref(false)
const userList = ref<UserItem[]>([])
const userSearchText = ref('')
const selectedUser = ref<UserItem | null>(null)
let userLoadPromise: Promise<void> | null = null

const salesDetails = ref<SalesDetailItem[]>([])
const selectedDetailRows = ref<SalesDetailItem[]>([])
const saving = ref(false)

const productDialogVisible = ref(false)
const productTableLoading = ref(false)
const productList = ref<ProductListItem[]>([])
const selectedProducts = ref<ProductListItem[]>([])
const DEFAULT_UNIT_OPTIONS = ['箱', '个', '套', '台', '条', '包', '瓶', '袋', '件']
const productUnitOptions = ref<string[]>([])

const unitOptions = ref<UnitItem[]>([])
let unitLoadPromise: Promise<void> | null = null

const productSearchForm = reactive({
    keyword: '',
    unit: '',
})

const productPagination = reactive({
    pageindex: 1,
    pagesize: 10,
    total: 0,
})

const PRODUCT_PRICE_FIELDS = [
    'productOutMoney',
    'productoutmoney',
    'productSalePrice',
    'productSaleMoney',
    'salesPrice',
    'salePrice',
    'outPrice',
    'productInmoney',
    'productInMoney',
    'productPrice',
    'price',
    'unitPrice',
]

const normalizePriceValue = (value: any): number | null => {
    if (value === undefined || value === null || value === '') return null
    const num = Number(value)
    if (Number.isNaN(num) || !Number.isFinite(num)) return null
    return num
}

const resolveProductPrice = (product: Record<string, any>): number | null => {
    for (const key of PRODUCT_PRICE_FIELDS) {
        const price = normalizePriceValue(product?.[key])
        if (price !== null) return price
    }
    return null
}

const formatProductPrice = (product: Record<string, any>) => {
    const price = resolveProductPrice(product)
    return (price ?? 0).toFixed(2)
}

const loadCustomers = async () => {
    if (!customerLoadPromise) {
        customerLoadPromise = (async () => {
            try {
                const res = await myaxios.get('/api/Customer/GetCustomer', {
                    params: {
                        pageindex: 1,
                        pagesize: 1000,
                    },
                })
                if (res.data.code === 200) {
                    customerOptions.value = res.data.data?.data || []
                }
            } catch (error) {
                console.error('获取客户列表失败:', error)
            }
        })()
    }
    await customerLoadPromise
}

const loadUnitOptions = async () => {
    if (!unitLoadPromise) {
        unitLoadPromise = (async () => {
            try {
                const res = await myaxios.get('/api/Unit/GetUnitList')
                if (res.data.code === 200 || res.data.success) {
                    const units = res.data.data || []
                    unitOptions.value = units
                        .filter((unit: any) => unit.unitState === 1 || unit.unitState === undefined)
                        .map((unit: any) => ({
                            unitId: unit.unitId,
                            unitCode: unit.unitCode || '',
                            unitName: unit.unitName || '',
                            unitState: unit.unitState,
                        }))
                }
            } catch (error) {
                console.error('获取单位列表失败:', error)
                unitOptions.value = DEFAULT_UNIT_OPTIONS.map((name, index) => ({
                    unitId: index + 1,
                    unitCode: name,
                    unitName: name,
                    unitState: 1,
                }))
            }
        })()
    }
    await unitLoadPromise
}

const buildOrgNameMap = (nodes: OrganizationItem[]) => {
    const map: Record<string, string> = {}
    const traverse = (list: OrganizationItem[]) => {
        list.forEach((item) => {
            map[String(item.organizationId)] = item.organizationName
            if (item.children && item.children.length) {
                traverse(item.children)
            }
        })
    }
    traverse(nodes)
    orgNameMap.value = map
}

const applyOrgNameToUsers = () => {
    if (!userList.value.length) return
    userList.value = userList.value.map((item) => ({
        ...item,
        organizationName:
            item.organizationName ||
            (item.organizationId ? orgNameMap.value[String(item.organizationId)] : '') ||
            '',
    }))
}

const normalizeSalesOrderId = (value: any): string | number | null => {
    if (value === undefined || value === null) return null
    if (Array.isArray(value)) return normalizeSalesOrderId(value[0])
    return value as string | number
}

const normalizeOrganizationNodes = (nodes: any[]): OrganizationItem[] => {
    const list: OrganizationItem[] = []
    const traverse = (items: any[]) => {
        items.forEach((item) => {
            const normalized: OrganizationItem = {
                ...item,
                organizationId: item.organizationId ?? item.id ?? item.value,
                organizationName: item.organizationName ?? item.label ?? item.name ?? '',
                organizationParentId:
                    item.organizationParentId ??
                    item.parentId ??
                    item.pid ??
                    item.parent ??
                    null,
                children: [],
            }
            list.push(normalized)
            if (item.children && item.children.length) {
                traverse(item.children)
            }
        })
    }
    traverse(nodes)
    return list
}

const buildOrgTree = (list: OrganizationItem[]): OrganizationItem[] => {
    const nodeMap = new Map<string | number, OrganizationItem>()
    const tree: OrganizationItem[] = []

    list.forEach((item) => {
        const normalized: OrganizationItem = {
            ...item,
            children: item.children ? [...item.children] : [],
        }
        nodeMap.set(normalized.organizationId, normalized)
    })

    nodeMap.forEach((item) => {
        const parentId = item.organizationParentId
        if (parentId && nodeMap.has(parentId)) {
            const parent = nodeMap.get(parentId)!
            parent.children = parent.children || []
            parent.children.push(item)
        } else {
            tree.push(item)
        }
    })

    return tree
}

const loadOrganizations = async () => {
    if (!orgLoadPromise) {
        orgLoadPromise = (async () => {
            try {
                const res = await myaxios.get('api/Supplier/GetOrganization')
                if (res.data.code === 200) {
                    const rawList = res.data.data || []
                    const normalizedList = normalizeOrganizationNodes(rawList)
                    const treeData = buildOrgTree(normalizedList)
                    orgTreeData.value = treeData.length ? treeData : normalizedList
                    buildOrgNameMap(orgTreeData.value)
                    applyOrgNameToUsers()
                }
            } catch (error) {
                console.error('获取部门失败:', error)
            }
        })()
    }
    await orgLoadPromise
}

const loadUsers = async () => {
    if (!userLoadPromise) {
        userLoadPromise = (async () => {
            try {
                const res = await myaxios.get('api/Supplier/GetUser')
                if (res.data.code === 200) {
                    userList.value = (res.data.data || []).map((item: UserItem) => ({
                        ...item,
                        organizationName:
                            item.organizationName ||
                            (item.organizationId ? orgNameMap.value[String(item.organizationId)] : '') ||
                            '',
                    }))
                }
            } catch (error) {
                console.error('获取用户失败:', error)
            }
            applyOrgNameToUsers()
        })()
    }
    await userLoadPromise
}

const formatDateValue = (value: any) => {
    if (!value) return ''
    if (typeof value === 'string') {
        if (value.includes('T')) {
            return value.slice(0, 10)
        }
        return value
    }
    return ''
}

const applySalesBaseInfo = (info: any) => {
    if (!info) return
    salesForm.salesOrderNo = info.salesOrderNo || info.SalesOrderNo || salesForm.salesOrderNo || ''
    salesForm.salesOrderDate =
        formatDateValue(info.salesOrderDate || info.SalesOrderDate) ||
        salesForm.salesOrderDate ||
        ''
    const customerIdValue = info.customerId ?? info.CustomerId ?? salesForm.customerId ?? ''
    salesForm.customerId = String(customerIdValue || '')
    const customerNameValue = info.customerName || info.CustomerName || ''
    if (customerNameValue) {
        salesForm.customerName = customerNameValue
    }
    salesForm.salesContact = info.salesContact || info.contact || salesForm.salesContact || ''
    salesForm.salesContactPhone =
        info.salesContactPhone || info.contactPhone || salesForm.salesContactPhone || ''
    salesForm.organizationId = String(info.organizationId ?? info.OrganizationId ?? salesForm.organizationId ?? '')
    salesForm.organizationName =
        info.organizationName || info.OrganizationName || info.salesDepartment || salesForm.organizationName || ''
    salesForm.userId = String(info.userId ?? info.UserId ?? salesForm.userId ?? '')
    salesForm.userName = info.userName || info.UserName || info.salesUser || salesForm.userName || ''
    salesForm.remark = info.remark || info.salesRemark || salesForm.remark || ''
}

const buildUnitGroupsFromSingleUnit = (unit: string): UnitOptionGroup[] => {
    if (!unit) return []
    return [
        {
            label: '当前单位',
            options: [
                {
                    label: unit,
                    value: unit,
                },
            ],
        },
    ]
}

const transformDetailResponse = (detail: any): SalesDetailItem => {
    console.log('转换明细数据，原始数据:', detail)

    const productId =
        detail.productId ??
        detail.productID ??
        detail.id ??
        detail.ProductId ??
        ''
    const productName = detail.productName || detail.ProductName || detail.goodsName || ''
    const productCode = detail.productCode || detail.ProductCode || detail.goodsCode || ''
    const specification =
        detail.specificationModel ||
        detail.productSpecification ||
        detail.productUnit ||
        detail.specification ||
        detail.productUnitName ||
        ''
    const unit =
        detail.unitName ||
        detail.unitDisplayName ||
        detail.unit ||
        detail.productUnit ||
        detail.productSpecification ||
        ''

    // 处理数量 - 确保是有效的数字，不能为 null（el-input-number 需要数字类型）
    const quantityRaw = detail.quantity ?? detail.salesQuantity ?? detail.salesCount ?? 0
    const quantity = Number(quantityRaw)
    const normalizedQuantity = (Number.isFinite(quantity) && !isNaN(quantity) && quantity > 0) ? quantity : (quantity > 0 ? quantity : 1)

    // 处理单价 - 根据 Swagger 文档，字段名是 salePrice（不是 salesPrice）
    const unitPriceRaw = detail.salePrice ?? detail.salesPrice ?? detail.unitPrice ?? detail.salesUnitPrice ?? 0
    const unitPrice = Number(unitPriceRaw)
    let normalizedUnitPrice = Number.isFinite(unitPrice) && !isNaN(unitPrice) && unitPrice >= 0 ? unitPrice : 0

    // 处理金额
    let amountValue =
        detail.amount ??
        detail.totalAmount ??
        detail.totalPrice ??
        detail.salesAmount
    let amount = Number(amountValue)
    if (amountValue == null || isNaN(amount)) {
        amount = Number((normalizedQuantity * normalizedUnitPrice).toFixed(2))
    } else {
        amount = Number(amount.toFixed ? amount.toFixed(2) : amount)
    }

    // 如果数量大于0，但单价与金额不匹配（或单价为0），则根据金额重新推算单价
    if (normalizedQuantity > 0) {
        const derivedPrice = Number((amount / normalizedQuantity).toFixed(4))
        const priceDiff = Math.abs(derivedPrice - normalizedUnitPrice)
        const mismatch =
            normalizedUnitPrice === 0 ||
            (derivedPrice > 0 && priceDiff / derivedPrice > 0.2) ||
            priceDiff >= 1
        if (derivedPrice > 0 && mismatch) {
            normalizedUnitPrice = derivedPrice
        }
    }

    // 使用最终单价重新计算金额，保证与展示一致
    amount = Number((normalizedQuantity * normalizedUnitPrice).toFixed(2))

    const transformed = {
        lineId: `${detail.salesOrderDetailId ?? detail.detailId ?? detail.lineId ?? productId}-${Date.now()}-${Math.random()}`,
        salesOrderDetailId: detail.salesOrderDetailId ?? detail.detailId ?? detail.lineId ?? null,
        productId: productId || '',
        productName,
        productCode,
        specificationModel: specification,
        specification: specification,
        unitName: unit,
        unit: unit || '',
        unitGroups: buildUnitGroupsFromSingleUnit(unit),
        productTypeName: detail.productTypeName || detail.ProductTypeName || '',
        currentStock: Number(detail.currentInventory ?? detail.currentStock ?? 0),
        quantity: normalizedQuantity,
        unitPrice: normalizedUnitPrice,
        amount: amount || 0,
        remark: detail.remark || detail.memo || '',
    }

    console.log('转换后的明细项:', transformed)
    return transformed
}

const unwrapDetailList = (payload: any): any[] | null => {
    if (!payload) return null
    let list = payload
    if (typeof list === 'string') {
        try {
            list = JSON.parse(list)
        } catch (err) {
            console.warn('解析明细字符串失败:', err, list)
            return null
        }
    }
    if (Array.isArray(list)) return list
    if (Array.isArray(list?.records)) return list.records
    if (Array.isArray(list?.data)) return list.data
    if (Array.isArray(list?.rows)) return list.rows
    if (Array.isArray(list?.list)) return list.list
    if (Array.isArray(list?.items)) return list.items
    if (Array.isArray(list?.Details)) return list.Details
    if (Array.isArray(list?.salesDetails)) return list.salesDetails
    if (Array.isArray(list?.SalesDetails)) return list.SalesDetails
    if (Array.isArray(list?.salesOrderDetails)) return list.salesOrderDetails
    if (Array.isArray(list?.SalesOrderDetails)) return list.SalesOrderDetails
    return null
}

const extractDetailList = (data: any): any[] => {
    const candidates = [
        data?.goodsDetails,
        data?.GoodsDetails,
        data?.salesDetails,
        data?.SalesDetails,
        data?.salesOrderDetails,
        data?.SalesOrderDetails,
        data?.details,
        data?.detail,
        data?.detailList,
        data?.DetailList,
        data?.items,
        data?.Items,
        data?.records,
        data?.Records,
        data?.data,
        data?.Data,
        data?.list,
        data?.List,
        data?.result,
        data?.Result,
        data?.salesOrder?.goodsDetails,
        data?.salesOrder?.salesDetails,
        data?.salesOrder?.salesOrderDetails,
        data?.salesOrder?.detailList,
        data?.salesOrder?.details,
        data?.baseInfo?.goodsDetails,
        data?.baseInfo?.salesDetails,
        data?.baseInfo?.salesOrderDetails,
        data?.baseInfo?.detailList,
        data?.baseInfo?.details,
    ]

    console.log('尝试提取明细数据，候选路径数量:', candidates.length)
    for (let i = 0; i < candidates.length; i++) {
        const candidate = candidates[i]
        if (candidate) {
            console.log(`尝试路径 ${i}:`, Object.keys(data || {}).find(key => data[key] === candidate), candidate)
        }
        const list = unwrapDetailList(candidate)
        if (list && list.length) {
            console.log(`找到明细数据，路径索引: ${i}`, list)
            return list
        }
    }
    console.warn('所有路径都未找到明细数据，data结构:', Object.keys(data || {}))
    return []
}

const requestSalesOrderDetail = async (url: string, id: string | number) => {
    return myaxios.get(url, {
        params: { salesOrderId: id },
    })
}

const loadSalesOrderDetail = async (id: string | number) => {
    if (!id) return
    detailLoading.value = true
    try {
        // 尝试多个可能的接口路径
        let res = await requestSalesOrderDetail('/api/SalesOrder/GetSalesOrderDetail', id).catch(
            () => null,
        )
        if (!res) {
            res = await requestSalesOrderDetail('/api/SalesOrder/GetSalesOrderDetails', id).catch(
                () => null,
            )
        }
        if (!res) {
            res = await requestSalesOrderDetail('/api/SalesOrder/DetailSalesOrder', id).catch(
                () => null,
            )
        }
        if (!res) {
            ElMessage.error('获取销售订单详情失败：接口不存在')
            return
        }

        const result = res.data || {}
        console.log('销售订单详情接口响应:', result)

        if (result.code === 200) {
            const data = result.data || {}
            console.log('销售订单详情数据:', data)
            console.log('销售订单详情数据完整结构:', JSON.stringify(data, null, 2))

            const baseInfo = data.salesOrder || data.baseInfo || data
            console.log('基础信息:', baseInfo)
            applySalesBaseInfo(baseInfo)

            // 处理明细数据 - 尝试多种可能的路径
            let detailList = extractDetailList(data)
            console.log('第一次提取的明细列表:', detailList)

            // 如果第一次没找到，尝试从 baseInfo 中提取
            if ((!detailList || detailList.length === 0) && baseInfo) {
                console.log('从 baseInfo 中提取明细:', baseInfo)
                detailList = extractDetailList(baseInfo)
                console.log('从 baseInfo 提取的明细列表:', detailList)
            }

            // 如果还是没找到，尝试直接从 data 的各个可能路径查找
            if ((!detailList || detailList.length === 0)) {
                console.log('尝试直接查找明细数据...')
                const directPaths = [
                    data.details,
                    data.salesOrderDetails,
                    data.salesDetails,
                    data.goodsDetails,
                    data.detailList,
                    data.items,
                    data.list,
                ]

                for (const path of directPaths) {
                    if (Array.isArray(path) && path.length > 0) {
                        console.log('找到直接路径的明细数据:', path)
                        detailList = path
                        break
                    }
                }
            }

            // 如果详情接口未返回明细数据，尝试调用单独的明细接口
            if ((!detailList || detailList.length === 0)) {
                console.log('详情接口未返回明细数据，尝试调用单独的明细接口...')
                try {
                    // 尝试调用单独的明细接口（注意：这个接口可能返回的是明细列表，不是包装在对象中）
                    const detailRes = await myaxios.get('/api/SalesOrder/GetSalesOrderDetails', {
                        params: { salesOrderId: id },
                    }).catch(() => null)

                    if (detailRes && detailRes.data) {
                        console.log('明细接口响应:', detailRes.data)
                        const detailResult = detailRes.data

                        // 如果返回的是标准格式 { code: 200, data: [...] }
                        if (detailResult.code === 200) {
                            const detailData = detailResult.data
                            // 如果 data 是数组，直接使用
                            if (Array.isArray(detailData)) {
                                detailList = detailData
                                console.log('明细接口返回数组，直接使用:', detailList)
                            } else {
                                // 如果 data 是对象，尝试提取
                                detailList = extractDetailList(detailData)
                                console.log('从明细接口对象中提取的明细列表:', detailList)
                            }
                        } else if (Array.isArray(detailResult)) {
                            // 如果直接返回数组
                            detailList = detailResult
                            console.log('明细接口直接返回数组:', detailList)
                        } else if (Array.isArray(detailResult.data)) {
                            // 如果返回 { data: [...] }
                            detailList = detailResult.data
                            console.log('从明细接口的 data 字段提取:', detailList)
                        }
                    }
                } catch (detailError) {
                    console.warn('调用明细接口失败:', detailError)
                }
            }

            if (Array.isArray(detailList) && detailList.length > 0) {
                salesDetails.value = detailList.map((item: any) => {
                    const transformed = transformDetailResponse(item)
                    console.log('转换后的明细项:', transformed)
                    return transformed
                })
                console.log('最终销售明细数据:', salesDetails.value, '数量:', salesDetails.value.length)
                ElMessage.success(`已加载 ${salesDetails.value.length} 条销售明细`)
            } else {
                salesDetails.value = []
                console.warn('未找到任何明细数据')
                console.warn('data的完整结构:', JSON.stringify(data, null, 2))
                console.warn('baseInfo的完整结构:', JSON.stringify(baseInfo, null, 2))
                // 不显示警告消息，因为可能是正常的（新订单没有明细）
            }
        } else {
            ElMessage.error(result.message || '获取销售订单详情失败')
        }
    } catch (error) {
        console.error('获取销售订单详情失败:', error)
        ElMessage.error('获取销售订单详情失败，请稍后重试')
    } finally {
        detailLoading.value = false
    }
}

const filteredOrgTree = computed(() => {
    if (!orgSearchText.value) return orgTreeData.value
    const keyword = orgSearchText.value.toLowerCase()

    const filterTree = (nodes: OrganizationItem[]): OrganizationItem[] => {
        const res: OrganizationItem[] = []
        nodes.forEach((node) => {
            const match = node.organizationName.toLowerCase().includes(keyword)
            const children = node.children ? filterTree(node.children) : []
            if (match || children.length) {
                res.push({ ...node, children })
            }
        })
        return res
    }

    return filterTree(orgTreeData.value)
})

const filteredUserList = computed(() => {
    let list = userList.value
    if (salesForm.organizationId) {
        list = list.filter(
            (u) => u.organizationId && String(u.organizationId) === salesForm.organizationId,
        )
    }
    if (userSearchText.value) {
        const kw = userSearchText.value.toLowerCase()
        list = list.filter((u) => u.userName.toLowerCase().includes(kw))
    }
    return list
})

const openOrgDialog = () => {
    orgDialogVisible.value = true
}

const handleSelectOrg = (node: OrganizationItem) => {
    selectedOrgNode.value = node
}

const confirmOrg = () => {
    if (!selectedOrgNode.value) {
        ElMessage.warning('请先选择部门')
        return
    }
    salesForm.organizationId = String(selectedOrgNode.value.organizationId)
    salesForm.organizationName = selectedOrgNode.value.organizationName
    clearUserSelection()
    orgDialogVisible.value = false
}

const openUserDialog = () => {
    if (!salesForm.organizationName) {
        ElMessage.warning('请先选择销售部门')
        return
    }
    userDialogVisible.value = true
}

const handleSelectUser = (row: UserItem) => {
    selectedUser.value = row
}

const confirmUser = () => {
    if (!selectedUser.value) {
        ElMessage.warning('请先选择人员')
        return
    }
    salesForm.userId = String(selectedUser.value.userId)
    salesForm.userName = selectedUser.value.userName
    userDialogVisible.value = false
}

const handleCustomerChange = (value: string | number) => {
    const target = customerOptions.value.find((item) => String(item.customerId) === String(value))
    if (target) {
        salesForm.customerName = target.customerName
        salesForm.salesContact = target.linkMan || salesForm.salesContact
        salesForm.salesContactPhone = target.linkPhone || salesForm.salesContactPhone
    } else {
        salesForm.customerName = ''
    }
}

const resetForm = () => {
    if (currentSalesOrderId.value) {
        loadSalesOrderDetail(currentSalesOrderId.value)
        return
    }
    salesForm.salesOrderNo = ''
    salesForm.salesOrderDate = ''
    salesForm.customerId = ''
    salesForm.customerName = ''
    salesForm.salesContact = ''
    salesForm.salesContactPhone = ''
    salesForm.organizationId = ''
    salesForm.organizationName = ''
    salesForm.userId = ''
    salesForm.userName = ''
    salesForm.remark = ''
    salesDetails.value = []
}

const handleSave = async () => {
    if (!isEditMode.value) {
        return
    }
    if (!salesFormRef.value) return
    const valid = await salesFormRef.value.validate().catch(() => false)
    if (!valid) return
    if (!salesDetails.value.length) {
        ElMessage.warning('请至少添加一条销售明细')
        return
    }

    await nextTick()
    await nextTick()

    salesDetails.value.forEach((item) => {
        let quantity: any = item.quantity
        if (quantity == null || quantity === undefined || quantity === '') {
            quantity = 0
        } else if (typeof quantity !== 'number') {
            quantity = Number(quantity)
            if (isNaN(quantity)) {
                quantity = 0
            }
        }
        item.quantity = quantity

        let unitPrice: any = item.unitPrice
        if (unitPrice == null || unitPrice === undefined || unitPrice === '') {
            unitPrice = 0
        } else if (typeof unitPrice !== 'number') {
            unitPrice = Number(unitPrice)
            if (isNaN(unitPrice)) {
                unitPrice = 0
            }
        }
        item.unitPrice = unitPrice

        if (quantity > 0 && unitPrice > 0) {
            item.amount = quantity * unitPrice
        } else {
            item.amount = 0
        }
    })

    await nextTick()

    const validDetails = salesDetails.value.filter((item) => {
        const quantity = Number(item.quantity)
        if (isNaN(quantity) || !isFinite(quantity) || quantity <= 0) {
            return false
        }
        const unitPrice = Number(item.unitPrice)
        if (isNaN(unitPrice) || !isFinite(unitPrice) || unitPrice <= 0) {
            return false
        }
        return true
    })

    if (validDetails.length === 0) {
        ElMessage.warning('销售明细不能为空，请至少填写一条有效的明细（销售数量和销售单价必须大于0）')
        return
    }

    if (validDetails.length < salesDetails.value.length) {
        ElMessage.warning(`已过滤 ${salesDetails.value.length - validDetails.length} 条无效明细（数量或单价为0），仅保存有效明细`)
    }

    const detailPayload = validDetails.map((item, index) => {
        const specification = item.specificationModel || item.specification || ''
        const unit = item.unitName || item.unit || ''
        const quantity = Number(item.quantity)
        const unitPrice = Number(item.unitPrice)
        const amount = quantity * unitPrice

        return {
            lineNo: index + 1,
            productId: Number(item.productId),
            productCode: String(item.productCode || ''),
            productName: String(item.productName || ''),
            specificationModel: String(specification || ''),
            unitName: item.unitId ? Number(item.unitId) : null,
            unitDisplayName: String(unit || ''),
            productTypeName: String(item.productTypeName || ''),
            currentInventory: Number(item.currentStock ?? 0),
            quantity,
            salesQuantity: quantity,
            salesPrice: unitPrice,
            amount: Number(amount.toFixed(2)),
            salesAmount: Number(amount.toFixed(2)),
            remark: String(item.remark || ''),
            salesOrderDetailId: item.salesOrderDetailId ?? null,
        }
    })

    if (!detailPayload || detailPayload.length === 0) {
        ElMessage.error('销售明细不能为空，请至少添加一条有效的明细')
        return
    }

    const validTotalQuantity = validDetails.reduce((sum, item) => sum + Number(item.quantity ?? 0), 0)
    const validTotalAmount = validDetails.reduce((sum, item) => sum + Number(item.amount ?? 0), 0)

    const payload: any = {
        salesOrderNo: salesForm.salesOrderNo,
        salesOrderDate: salesForm.salesOrderDate
            ? new Date(salesForm.salesOrderDate).toISOString()
            : new Date().toISOString(),
        customerId: salesForm.customerId,
        customerName: salesForm.customerName,
        salesContact: salesForm.salesContact,
        salesContactPhone: salesForm.salesContactPhone,
        organizationId: salesForm.organizationId,
        organizationName: salesForm.organizationName,
        userId: salesForm.userId,
        userName: salesForm.userName,
        SalesOrderDepartment: salesForm.organizationName || '',
        SalesOrderUser: salesForm.userName || '',
        remark: salesForm.remark || '',
        salesOrderNote: salesForm.remark || ' ',
        SalesOrderNote: salesForm.remark || ' ',
        totalQuantity: Number(validTotalQuantity),
        totalAmount: Number(validTotalAmount.toFixed(2)),
        goodsDetails: detailPayload,
        salesDetails: detailPayload,
        SalesDetails: detailPayload,
        salesOrderDetails: detailPayload,
        SalesOrderDetails: detailPayload,
        detailList: detailPayload,
        Details: detailPayload,
    }

    if (!payload.SalesOrderUser) {
        ElMessage.error('请选择销售负责人')
        return
    }
    if (!payload.SalesOrderDepartment) {
        ElMessage.error('请选择销售部门')
        return
    }

    if (!currentSalesOrderId.value) {
        ElMessage.error('缺少销售订单ID，无法保存')
        return
    }

    saving.value = true
    try {
        payload.salesOrderId = currentSalesOrderId.value
        const res = await myaxios.put('/api/SalesOrder/UpdateSalesOrder', payload)
        const result = res.data || {}
        if (result.code === 200) {
            ElMessage.success(result.message || '销售订单修改成功')
            router.push('/GetSalesOrder')
        } else {
            const errorMsg = result.message || '修改失败，请检查数据是否正确'
            console.error('后端返回错误:', result)
            if (errorMsg.includes('明细') || errorMsg.includes('不能为空')) {
                ElMessage.error(`${errorMsg}。请确保所有明细的销售数量和销售单价都已填写且大于0`)
            } else {
                ElMessage.error(errorMsg)
            }
        }
    } catch (error: any) {
        console.error('保存销售订单失败:', error)
        console.error('错误详情:', {
            message: error?.message,
            response: error?.response?.data,
            status: error?.response?.status,
        })

        let errorMessage = '修改失败，请稍后重试'
        const errorData = error?.response?.data

        if (error?.response?.status === 400 && errorData?.errors) {
            const validationErrors: string[] = []
            Object.keys(errorData.errors).forEach((field) => {
                const fieldErrors = errorData.errors[field]
                if (Array.isArray(fieldErrors)) {
                    fieldErrors.forEach((msg: string) => {
                        validationErrors.push(msg)
                    })
                }
            })

            if (validationErrors.length > 0) {
                errorMessage = validationErrors.join('；')
                console.error('验证错误详情:', errorData.errors)
            } else {
                errorMessage = errorData.title || errorData.message || errorMessage
            }
        } else if (errorData) {
            errorMessage = errorData.message || errorData.error || errorData.title || errorMessage
        } else if (error?.message) {
            errorMessage = error.message
        }

        if (errorMessage.includes('明细') || errorMessage.includes('不能为空')) {
            ElMessage.error(`${errorMessage}。请确保所有明细的销售数量和销售单价都已填写且大于0`)
        } else if (errorMessage.includes('SalesOrderUser') || errorMessage.includes('销售负责人')) {
            ElMessage.error('请选择销售负责人')
        } else if (errorMessage.includes('SalesOrderDepartment') || errorMessage.includes('销售部门')) {
            ElMessage.error('请选择销售部门')
        } else {
            ElMessage.error(errorMessage)
        }
    } finally {
        saving.value = false
    }
}

const goBack = () => {
    router.push('/GetSalesOrder')
}

const gotoCreateCustomer = () => {
    router.push('/CreateCustomer')
}

const clearOrgSelection = () => {
    salesForm.organizationId = ''
    salesForm.organizationName = ''
    selectedOrgNode.value = null
    clearUserSelection()
}

const clearUserSelection = () => {
    salesForm.userId = ''
    salesForm.userName = ''
    selectedUser.value = null
}

const handleDetailSelectionChange = (rows: SalesDetailItem[]) => {
    selectedDetailRows.value = rows
}

const removeDetail = (index: number) => {
    salesDetails.value.splice(index, 1)
}

const removeSelectedDetails = () => {
    if (!selectedDetailRows.value.length) {
        ElMessage.warning('请选择需要移除的明细')
        return
    }
    salesDetails.value = salesDetails.value.filter(
        (item) => !selectedDetailRows.value.includes(item),
    )
    selectedDetailRows.value = []
    ElMessage.success('已移除选中的明细')
}

const updateDetailAmount = (row: SalesDetailItem) => {
    let quantity: number = 0
    if (row.quantity != null && row.quantity !== undefined) {
        quantity = typeof row.quantity === 'number' ? row.quantity : Number(row.quantity) || 0
        if (isNaN(quantity) || !isFinite(quantity)) {
            quantity = 0
        }
    }

    let unitPrice: number = 0
    if (row.unitPrice != null && row.unitPrice !== undefined) {
        unitPrice = typeof row.unitPrice === 'number' ? row.unitPrice : Number(row.unitPrice) || 0
        if (isNaN(unitPrice) || !isFinite(unitPrice)) {
            unitPrice = 0
        }
    }

    row.amount = Number((quantity * unitPrice).toFixed(2))

    if (isNaN(row.amount) || !isFinite(row.amount)) {
        row.amount = 0
    }
}

const handleSpecificationChange = (row: SalesDetailItem) => {
    row.unitName = row.specificationModel || row.unitName
}

const totalProductKinds = computed(() => salesDetails.value.length)
const totalProductQuantity = computed(() =>
    salesDetails.value.reduce((sum, item) => sum + (item.quantity || 0), 0),
)
const totalProductAmount = computed(() =>
    salesDetails.value.reduce((sum, item) => sum + (item.amount || 0), 0),
)

const openProductDialog = () => {
    productDialogVisible.value = true
    selectedProducts.value = []
    if (!productList.value.length) {
        searchProducts()
    }
}

const buildUnitGroupsFromProduct = (product: ProductListItem): UnitOptionGroup[] => {
    const groups: UnitOptionGroup[] = []
    const mainUnits: UnitOption[] = []
    const assistUnits: UnitOption[] = []

    const normalizeUnit = (unitValue: any) => {
        if (!unitValue) return ''
        if (typeof unitValue === 'string') return unitValue
        if (typeof unitValue === 'object') {
            return (
                unitValue.unitName ||
                unitValue.unit ||
                unitValue.label ||
                unitValue.name ||
                ''
            )
        }
        return String(unitValue)
    }

    const mainUnitName = normalizeUnit(
        product.productUnit || product.mainUnit || product.mainUnitName || product.unitDisplay,
    )
    if (mainUnitName) {
        mainUnits.push({
            label: mainUnitName,
            value: mainUnitName,
            description: '主单位',
        })
    }

    const rawUnits =
        product.auxiliaryUnits ||
        product.assistUnits ||
        product.unitOptions ||
        product.unitList ||
        product.units ||
        []

    const candidates = Array.isArray(rawUnits) ? rawUnits : [rawUnits]
    candidates.forEach((unit: any, index: number) => {
        if (!unit) return
        const label = normalizeUnit(unit)
        if (!label) return
        const convertQty =
            unit.convertQty ||
            unit.convertQuantity ||
            unit.rate ||
            (unit.conversion && unit.conversion.rate) ||
            null
        const desc =
            unit.description ||
            unit.convertText ||
            unit.convertDesc ||
            (convertQty && mainUnitName ? `= ${convertQty} ${mainUnitName}` : '') ||
            ''
        assistUnits.push({
            label,
            value: label,
            description: desc || `辅助单位${assistUnits.length + 1}`,
        })
    })

    if (mainUnits.length) {
        groups.push({ label: '主单位', options: mainUnits })
    }
    if (assistUnits.length) {
        groups.push({ label: '辅助单位', options: assistUnits })
    }
    return groups.length ? groups : [{ label: '主单位', options: [{ label: mainUnitName || '主单位', value: mainUnitName || '' }] }]
}

const normalizeProductRecord = (record: any): ProductListItem | null => {
    const productId =
        record.productId ??
        record.productID ??
        record.id ??
        record.productid ??
        record.ProductId ??
        null
    if (!productId) return null

    const specification = record.productUnit ?? record.mainUnit ?? record.mainUnitName ?? record.unit ?? ''
    const unit = record.productspecification ?? record.productSpecification ?? record.specification ?? record.specificationModel ?? record.spec ?? ''

    const productName = record.productName ?? record.name ?? ''
    const productCode = record.productCode ?? record.code ?? ''

    return {
        ...record,
        productId,
        productName,
        productCode,
        producttypeName: record.producttypeName ?? record.productTypeName ?? record.typeName,
        productUnit: specification,
        mainUnit: specification,
        unitDisplay: specification,
        productspecification: unit,
        productSpecification: unit,
        specification: unit,
        inventoryCurrtnumber:
            record.inventoryCurrtnumber ?? record.currentInventory ?? record.stock ?? 0,
        productOutMoney:
            record.productOutMoney ??
            record.productoutmoney ??
            record.productSalePrice ??
            record.salesPrice ??
            record.salePrice ??
            record.outPrice ??
            record.productInmoney ??
            record.productInMoney ??
            record.productPrice ??
            record.price ??
            0,
    }
}

const buildProductKey = (item: ProductListItem) =>
    `${item.productId ?? ''}__${item.productCode ?? ''}__${item.specification ?? ''}`

const normalizeProductList = (list: any[]): ProductListItem[] => {
    const map = new Map<string, ProductListItem>()
    list.forEach((item) => {
        const normalized = normalizeProductRecord(item)
        if (!normalized) return
        const key = buildProductKey(normalized)
        if (!map.has(key)) {
            map.set(key, normalized)
        }
    })
    return Array.from(map.values())
}

const enrichProductUnits = (list: ProductListItem[]) => {
    const dynamicUnits = new Set<string>()
    list.forEach((item) => {
        const unit =
            item.productUnit ||
            item.mainUnit ||
            item.mainUnitName ||
            item.unitDisplay ||
            ''
        if (unit) {
            dynamicUnits.add(unit)
            item.unitDisplay = unit
        }
    })
    const orderedUnits: string[] = []
    DEFAULT_UNIT_OPTIONS.forEach((unit) => {
        orderedUnits.push(unit)
    })
    dynamicUnits.forEach((unit) => {
        if (!orderedUnits.includes(unit)) {
            orderedUnits.push(unit)
        }
    })
    productUnitOptions.value = orderedUnits
}

const searchProducts = async () => {
    productTableLoading.value = true
    try {
        const res = await myaxios.get('/api/Product/GetProduct', {
            params: {
                Pageindex: productPagination.pageindex,
                PageSize: productPagination.pagesize,
                ProductName: productSearchForm.keyword,
                ProductUnit: productSearchForm.unit,
            },
        })
        if (res.data.code === 200) {
            const rawList = res.data.data?.data || []
            const normalizedList = normalizeProductList(rawList)
            productList.value = normalizedList
            productPagination.total = res.data.data?.listCount || 0
            enrichProductUnits(productList.value)
        } else {
            ElMessage.error(res.data.message || '获取货品失败')
        }
    } catch (error) {
        console.error('获取货品失败:', error)
        ElMessage.error('获取货品失败')
    } finally {
        productTableLoading.value = false
    }
}

const resetProductSearch = () => {
    productSearchForm.keyword = ''
    productSearchForm.unit = ''
    productPagination.pageindex = 1
    searchProducts()
}

const handleProductSelectionChange = (rows: ProductListItem[]) => {
    selectedProducts.value = rows
}

const handleProductSizeChange = (size: number) => {
    productPagination.pagesize = size
    productPagination.pageindex = 1
    searchProducts()
}

const handleProductCurrentChange = (page: number) => {
    productPagination.pageindex = page
    searchProducts()
}

const transformProductToDetail = (product: ProductListItem): SalesDetailItem => {
    const unitGroups = buildUnitGroupsFromProduct(product)

    const specification = product.productUnit || product.mainUnit || product.unitDisplay || ''
    const unit = product.productspecification || product.productSpecification || product.specification || ''

    const defaultUnit =
        unit ||
        unitGroups[0]?.options[0]?.value ||
        ''

    const basePrice = resolveProductPrice(product)
    return {
        lineId: `${product.productId}-${Date.now()}`,
        productId: product.productId,
        productName: product.productName,
        productCode: product.productCode,
        specificationModel: specification,
        unitName: unit,
        unit: defaultUnit,
        unitGroups,
        productTypeName: product.producttypeName,
        currentStock: product.inventoryCurrtnumber || 0,
        quantity: null as any,
        unitPrice: basePrice || 0,
        amount: 0,
        remark: '',
    }
}

const confirmProductSelection = () => {
    if (!selectedProducts.value.length) {
        ElMessage.warning('请选择需要添加的货品')
        return
    }
    let added = 0
    let skipped = 0
    selectedProducts.value.forEach((item) => {
        const existed = salesDetails.value.find((detail) => detail.productId === item.productId)
        if (existed) {
            skipped++
            const syncedPrice = resolveProductPrice(item)
            if (syncedPrice !== null && syncedPrice !== undefined) {
                existed.unitPrice = syncedPrice
                updateDetailAmount(existed)
            }
            return
        }
        salesDetails.value.push(transformProductToDetail(item))
        added++
    })
    productDialogVisible.value = false
    selectedProducts.value = []
    if (added) {
        ElMessage.success(`成功添加 ${added} 个货品${skipped ? `，跳过 ${skipped} 个重复货品` : ''}`)
    } else {
        ElMessage.warning('所选货品已全部存在')
    }
}

onMounted(async () => {
    const salesOrderId = normalizeSalesOrderId(
        route.query.salesOrderId ?? route.params.salesOrderId ?? null,
    )
    if (!salesOrderId) {
        ElMessage.error('缺少销售订单ID')
        router.push('/GetSalesOrder')
        return
    }
    currentSalesOrderId.value = salesOrderId

    const baseTasks = [
        loadCustomers(),
        loadOrganizations(),
        loadUsers(),
        loadUnitOptions(),
    ]

    await Promise.allSettled([
        ...baseTasks,
        loadSalesOrderDetail(salesOrderId),
    ])
})
</script>

<style scoped>
.common-layout {
    padding: 20px;
    position: relative;
}

.card-block {
    margin-bottom: 16px;
}

.card-title {
    font-weight: bold;
}

.inline-input {
    display: flex;
    align-items: center;
    gap: 8px;
}

.link-btn {
    padding: 0 4px;
}

.detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.detail-actions {
    display: flex;
    gap: 12px;
}

.detail-summary {
    margin-top: 16px;
    padding: 12px 16px;
    background: #f5f7fa;
    border-radius: 4px;
    display: flex;
    gap: 24px;
    color: #606266;
}

.product-search-form {
    margin-bottom: 16px;
}

.product-pagination {
    margin-top: 16px;
    text-align: right;
}

.unit-desc {
    color: #909399;
    margin-left: 6px;
    font-size: 12px;
}

.dialog-search {
    margin-bottom: 12px;
}

.fixed-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    border-top: 1px solid #e4e7ed;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.footer-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 12px 20px;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}
</style>
